<template>
  <div class="page">
    <h2>用量监控</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按名称或编码搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="filterDept" placeholder="全部科室" style="width:180px">
        <el-option label="全部科室" :value="''" />
        <el-option v-for="d in depts" :key="d" :label="d" :value="d" />
      </el-select>

      <el-select v-model="filterRisk" placeholder="风险等级" style="width:140px">
        <el-option label="全部" :value="''" />
        <el-option label="高风险" value="high" />
        <el-option label="中风险" value="medium" />
        <el-option label="低风险" value="low" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="refresh">刷新</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <div class="muted">提示：此页面为前端静态演示，数据为模拟假数据，仅用于展示用量监控的典型指标与交互。</div>

    <div class="metrics" style="margin-top:12px">
      <div class="card">
        <div class="num">{{ totalPrescriptions }}</div>
        <div class="label">总处方数（模拟）</div>
      </div>
      <div class="card">
        <div class="num">{{ totalDDD.toFixed(1) }}</div>
        <div class="label">总 DDD（定义日剂量）</div>
      </div>
      <div class="card">
        <div class="num">{{ alertsCount }}</div>
        <div class="label">异常警示数</div>
      </div>
      <div class="card">
        <div class="num">{{ topDrugName }}</div>
        <div class="label">最高用量药品</div>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="code" label="编码" width="120" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="department" label="科室" width="140" />
      <el-table-column prop="prescriptionsCount" label="处方数" width="110" />
      <el-table-column prop="totalQty" label="总用量" width="120">
        <template #default="{ row }">{{ row.totalQty }} {{ row.unit }}</template>
      </el-table-column>
      <el-table-column label="平均剂量" width="120">
        <template #default="{ row }">{{ row.avgDose }} {{ row.unit }}</template>
      </el-table-column>
      <el-table-column prop="dddPer1000" label="DDD/1000人日" width="150">
        <template #default="{ row }">{{ row.dddPer1000.toFixed(2) }}</template>
      </el-table-column>
      <el-table-column prop="risk" label="风险等级" width="120">
        <template #default="{ row }">
          <el-tag :type="row.risk==='high'? 'danger' : row.risk==='medium' ? 'warning' : 'info'">{{ row.risk==='high' ? '高' : row.risk==='medium' ? '中' : '低' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <el-button size="small" @click="openDetail(row.id)">详情</el-button>
          <el-button size="small" type="warning" @click="markReview(row.id)" style="margin-left:8px">标记复核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchMarkReview">批量标记复核</el-button>
      <el-button type="danger" @click="batchAlert">生成警示</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog title="药品用量详情" v-model="showDetail" width="700px">
      <div v-if="detailItem">
        <div style="display:flex;gap:16px;align-items:center">
          <div style="flex:1">
            <h3 style="margin:0">{{ detailItem.name }} ({{ detailItem.code }})</h3>
            <div class="muted">科室：{{ detailItem.department }} &nbsp; 单位：{{ detailItem.unit }} &nbsp; 风险：{{ detailItem.risk }}</div>
          </div>
          <div style="width:220px;text-align:right">
            <div style="font-size:20px;font-weight:600">总用量：{{ detailItem.totalQty }} {{ detailItem.unit }}</div>
            <div class="muted">DDD/1000人日：{{ detailItem.dddPer1000.toFixed(2) }}</div>
          </div>
        </div>

        <el-divider />

        <div>
          <h4>近期处方（示例）</h4>
          <el-table :data="detailItem.recent" style="width:100%" size="small">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="patient" label="患者" />
            <el-table-column prop="dose" label="单次剂量" width="120"> 
              <template #default="{ row }">{{ row.dose }} {{ detailItem.unit }}</template>
            </el-table-column>
            <el-table-column prop="qty" label="本次用量" width="120"> 
              <template #default="{ row }">{{ row.qty }} {{ detailItem.unit }}</template>
            </el-table-column>
            <el-table-column prop="note" label="备注" />
          </el-table>
        </div>

        <el-divider />

        <div>
          <h4>建议与说明</h4>
          <div class="muted">按网络常见的用量监控与处方审查实践，页面提供：超量预警（高剂量/累计量）、与 DDD 对比、按科室/人群分布检测、以及针对高风险药品的重点审查建议。</div>
          <ul style="margin-top:8px">
            <li>若单次剂量或日累计超过常规范围，建议人工复核处方与体重/肾功能等信息。</li>
            <li>对长期住院患者，应关注累计用量和药物相互作用。</li>
            <li>高风险药品（如抗凝、胰岛素、抗精神病药）应有独立监控规则与审签。</li>
          </ul>
        </div>
      </div>
      <template #footer>
        <el-button @click="showDetail=false">关闭</el-button>
        <el-button type="primary" @click="requestReview">申请复核</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const q = ref('');
const filterDept = ref('');
const filterRisk = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showDetail = ref(false);
const detailItem = ref(null);

const DEFAULT_USAGE = [
  { id:1, code:'D0001', name:'阿莫西林胶囊', department:'内科', unit:'粒', prescriptionsCount:120, totalQty:2400, avgDose:20, dddPer1000:12.5, risk:'low', recent:[{date:'2025-10-20',patient:'张三',dose:20,qty:20,note:''},{date:'2025-10-22',patient:'李四',dose:20,qty:40,note:'连续用药'}] },
  { id:2, code:'D0009', name:'氯雷他定片', department:'门诊', unit:'片', prescriptionsCount:80, totalQty:1120, avgDose:14, dddPer1000:6.8, risk:'low', recent:[{date:'2025-10-18',patient:'王五',dose:10,qty:10,note:''}] },
  { id:3, code:'D0008', name:'胰岛素注射液', department:'内分泌科', unit:'IU', prescriptionsCount:45, totalQty:4500, avgDose:100, dddPer1000:22.4, risk:'high', recent:[{date:'2025-10-23',patient:'赵六',dose:100,qty:100,note:'需监测血糖'}] },
  { id:4, code:'D0003', name:'布洛芬片', department:'急诊', unit:'片', prescriptionsCount:60, totalQty:720, avgDose:12, dddPer1000:9.3, risk:'medium', recent:[{date:'2025-10-21',patient:'钱七',dose:12,qty:24,note:''}] },
  { id:5, code:'D0010', name:'利伐沙班', department:'心内科', unit:'mg', prescriptionsCount:18, totalQty:360, avgDose:20, dddPer1000:15.7, risk:'high', recent:[{date:'2025-10-19',patient:'孙八',dose:20,qty:20,note:'抗凝药 - 注意出血风险'}] },

  { id:6, code:'D0002', name:'甲硝唑片', department:'外科', unit:'片', prescriptionsCount:95, totalQty:950, avgDose:10, dddPer1000:7.2, risk:'low', recent:[{date:'2025-10-17',patient:'周九',dose:10,qty:20,note:''}] },
  { id:7, code:'D0004', name:'奥司他韦', department:'儿科', unit:'粒', prescriptionsCount:32, totalQty:96, avgDose:3, dddPer1000:4.5, risk:'medium', recent:[{date:'2025-10-24',patient:'刘十',dose:3,qty:6,note:'儿童用量'}] },
  { id:8, code:'D0005', name:'阿立哌唑片', department:'精神科', unit:'mg', prescriptionsCount:55, totalQty:2750, avgDose:50, dddPer1000:18.1, risk:'high', recent:[{date:'2025-10-15',patient:'何十一',dose:50,qty:50,note:'监测症状'}] },
  { id:9, code:'D0006', name:'泮托拉唑钠', department:'消化内科', unit:'mg', prescriptionsCount:140, totalQty:7000, avgDose:50, dddPer1000:20.0, risk:'low', recent:[{date:'2025-10-14',patient:'施十二',dose:50,qty:100,note:''}] },
  { id:10, code:'D0007', name:'万古霉素注射液', department:'感染科', unit:'mg', prescriptionsCount:12, totalQty:6000, avgDose:500, dddPer1000:30.6, risk:'high', recent:[{date:'2025-10-16',patient:'袁十三',dose:500,qty:500,note:'重症感染'}] },
  { id:11, code:'D0011', name:'盐酸左氧氟沙星', department:'泌尿科', unit:'mg', prescriptionsCount:48, totalQty:1440, avgDose:30, dddPer1000:11.4, risk:'medium', recent:[{date:'2025-10-13',patient:'顾十四',dose:30,qty:30,note:''}] },
  { id:12, code:'D0012', name:'氯胺酮注射液', department:'神经内科', unit:'ml', prescriptionsCount:8, totalQty:80, avgDose:10, dddPer1000:9.8, risk:'medium', recent:[{date:'2025-10-12',patient:'宋十五',dose:10,qty:10,note:'麻醉相关'}] }
];

const data = ref([]);
onMounted(()=>{ data.value = JSON.parse(JSON.stringify(DEFAULT_USAGE)); });

const depts = computed(()=>{ const s=new Set(data.value.map(i=>i.department)); return Array.from(s); });

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.name.toLowerCase().includes(qq) || d.code.toLowerCase().includes(qq))) return false;
    if(filterDept.value && d.department !== filterDept.value) return false;
    if(filterRisk.value && d.risk !== filterRisk.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.id); });
function onSelectionChange(rows){ selectedRows.value = rows; }

const totalPrescriptions = computed(()=> data.value.reduce((s,i)=>s+i.prescriptionsCount,0));
const totalDDD = computed(()=> data.value.reduce((s,i)=>s + (i.dddPer1000||0),0));
const alertsCount = computed(()=> data.value.filter(i=>i.risk==='high').length);
const topDrugName = computed(()=>{ const top = data.value.slice().sort((a,b)=>b.totalQty-a.totalQty)[0]; return top? `${top.name}` : '-' });

function refresh(){ ElMessage.info('已刷新（模拟）'); }

function openDetail(id){ const it = data.value.find(x=>x.id===id); if(it){ detailItem.value = it; showDetail.value = true; } }
function markReview(id){ ElMessage.success('已标记为复核（模拟）'); }

function batchMarkReview(){ const ids = selectedIds.value.slice(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessage.success(`已标记 ${ids.length} 项为复核（模拟）`); }
function batchAlert(){ const ids = selectedIds.value.slice(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认为 ${ids.length} 项生成警示？`,'批量警示',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ ElMessage.success('已生成警示（模拟）'); })
  .catch(()=>{});
}

function requestReview(){ ElMessage.success('复核申请已提交（模拟）'); showDetail.value = false; }

function exportCSV(){ const csv=[['id','code','name','department','prescriptionsCount','totalQty','avgDose','unit','dddPer1000','risk'] , ...data.value.map(d=>[d.id,d.code,d.name,d.department,d.prescriptionsCount,d.totalQty,d.avgDose,d.unit,d.dddPer1000,d.risk])];
  const csvContent = csv.map(r=>r.map(c=>`"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'});
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href = url; a.download = 'usage_monitor.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
}

function onClear(){ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
.metrics{display:flex;gap:12px}
.card{background:#fff;border:1px solid #e6e6e6;padding:12px;border-radius:6px;min-width:160px}
.card .num{font-size:18px;font-weight:700}
.card .label{color:#888;margin-top:6px}
</style>
